package com.atguigu.gmall.order.service.impl;

import com.atguigu.gmall.common.util.UserAuthToUtil;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
        implements OrderInfoService {
    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Override
    public void updateOrderStatus(ProcessStatus originStatus, ProcessStatus modifyStatus, Long orderId, Long userId) {
        OrderInfo orderInfo = new OrderInfo();
        //设置订单最新状态
        orderInfo.setOrderStatus(modifyStatus.getOrderStatus().name());
        orderInfo.setProcessStatus(modifyStatus.name());

        orderInfo.setId(orderId);
        orderInfo.setUserId(userId);


        orderInfoMapper.updateOrderStatus(originStatus.name(), orderInfo);
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        Long userId = UserAuthToUtil.getUserAuthTo().getUserId();
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = Wrappers.
                lambdaQuery(OrderInfo.class)
                .eq(OrderInfo::getId, orderId)
                .eq(OrderInfo::getUserId, userId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);
        return orderInfo;
    }
    //更改订单状态为已经支付
    @Override
    public void updateStatusToPaid(String outTradeNo) {
        Long userId = getUserId(outTradeNo);
        ProcessStatus paid = ProcessStatus.PAID;
        orderInfoMapper.updateStatusToPaid(outTradeNo,userId,paid.name(),paid.getOrderStatus().name());
    }
    //将流水号切割得到用户id
    private static Long getUserId(String outTradeNo) {
        String userIdStr = outTradeNo.split("-")[2];
        Long userId = Long.valueOf(userIdStr);
        return userId;
    }

    @Override
    public OrderInfo getOrderInfoAndDetails(String outTradeNo) {
        Long userId = getUserId(outTradeNo);
        return orderInfoMapper.getOrderInfoAndDetails(outTradeNo,userId);

    }

    @Override
    public void updateOrderStatusToSpilt(Long orderId, Long userId, ProcessStatus processStatus) {
        orderInfoMapper.updateOrderStatusToSpilt(orderId,userId,processStatus.name(),processStatus.getOrderStatus().name());
    }

    @Override
    public void updateStatusByStock(Long orderId, ProcessStatus newProcessStatus) {
        orderInfoMapper.updateStatusByStock(orderId,newProcessStatus.name(),newProcessStatus.getOrderStatus().name());
    }
}




